package com.boot.modules.captcha.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.boot.common.constant.RedisConstant;
import com.boot.modules.captcha.service.CaptchaService;
import com.boot.util.RedisUtil;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.io.IOException;

@Slf4j
@RequiredArgsConstructor
@Service("captchaService")
public class CaptchaServiceImpl implements CaptchaService {

    private final RedisUtil redisUtil;

    @Override
    public void createCaptcha(HttpServletResponse response, String uuid) {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        ServletOutputStream outputStream = null;
        try {
            //创建一个验证码
            RandomGenerator randomGenerator = new RandomGenerator("0123456789", 4);
            LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100, 4, 600);
            lineCaptcha.setGenerator(randomGenerator);
            lineCaptcha.createCode();
            //写入到缓存(5分钟有效)
            String captchaKey = StrUtil.format(RedisConstant.User.CAPTCHA, uuid);
            redisUtil.set(captchaKey, lineCaptcha.getCode(), 300);
            outputStream = response.getOutputStream();
            lineCaptcha.write(outputStream);
        } catch (IOException e) {
            log.error("Captcha Jpg异常", e);
        }finally {
            if (outputStream != null){
                IoUtil.close(outputStream);
            }
        }
    }
}
